<template>
    <div>
        <el-row :gutter="20">
            <el-col :span="6">
                <el-card>
                    <el-input
                        placeholder="输入关键字进行过滤"
                        size="small"
                        v-model="filterText">
                   </el-input>
                  <el-tree
                    :props="props"
                    lazy
                    :load="loadNode"
                    :highlight-current="true"
                    :expand-on-click-node="false"
                    @node-click="handleNodeClick"
                    style="margin-top: 10px"
                   >
                 </el-tree>
                </el-card>
            </el-col>
             <el-col :span="18">
                <el-card>
                     <el-form :model="queryParams" ref="queryParams" :inline="true" label-width="100px">
                        <el-form-item label="登录账号：" prop="account">
                            <el-input v-model="queryParams.account" placeholder="登录账号" size="small"></el-input>
                        </el-form-item>
                        <el-form-item label="用户姓名：" prop="realName">
                            <el-input v-model="queryParams.realName" placeholder="用户姓名" size="small"></el-input>
                        </el-form-item>
                        <el-form-item >
                            <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
                            <el-button icon="el-icon-delete" size="small" @click="resetQuery('queryParams')">清空</el-button>
                        </el-form-item>
                    </el-form>
                   <el-row :gutter="10">
                        <el-col :span="24">
                            <div class="user-btns">
                                <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
                                <el-button type="danger" plain icon="el-icon-delete" size="small">删除</el-button>
                                <el-button type="info" plain icon="el-icon-user" size="small" @click="handleRoleSet">角色配置</el-button>
                                <el-button icon="el-icon-refresh" size="small" @click="handleReset">密码重置</el-button>
                                <el-button type="success" plain icon="el-icon-top" size="small" @click="handleImport">导入</el-button>
                                <el-button type="warning" plain icon="el-icon-bottom" size="small" @click="download()">导出</el-button>
                            </div>
                        </el-col>
                   </el-row>
                   <el-table :data="tableData" border style="width: 100%" size="small" ref="tableRef">
                        <el-table-column type="selection" width="50"></el-table-column>
                        <el-table-column type="index" label="#" width="50"></el-table-column>
                        <el-table-column label="登录账号" prop="name"></el-table-column>
                        <el-table-column label="用户姓名" prop="realName"></el-table-column>
                        <el-table-column label="所属角色" prop="roleName">
                            <template slot-scope="{row}">
                                <el-tag type="primary">{{row.roleName}}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="所属部门" prop="deptName">
                            <template slot-scope="{row}">
                                <el-tag type="primary">{{row.deptName}}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="300" align="center">
                            <template slot-scope="scope">
                                <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
                                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
                                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                     <el-pagination
                        v-show="total>0"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        background
                        :current-page="1"
                        :page-sizes="[10, 20, 30, 40,50,100]"
                        :page-size="10"
                        layout="total, sizes, prev, pager, next, jumper"
                        class="pagination-container"
                        :total="total">
                  </el-pagination>
                </el-card>
            </el-col>
        </el-row>

        <!-- 新增抽屉 -->
        <el-drawer
            title="新增"
            :visible.sync="drawer"
            direction="rtl"
            size="50%"
            :before-close="handleClose">
                <el-form :model="userForm" :rules="userRules" ref="userForm" label-width="100px" :disabled="mode==='view'">
                    <el-collapse>
                        <el-collapse-item>
                            <template slot="title">
                                <i class="el-icon-user-solid"></i>&nbsp;基础信息
                            </template>
                             <el-form-item prop="account" label="登录账号：" required>
                                <el-input clearable v-model="userForm.account" size="small" placeholder="请输入登录账号"></el-input>
                            </el-form-item>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item prop="password" label="密码：" required>
                                        <el-input clearable v-model="userForm.password" size="small" placeholder="请输入密码"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item prop="password2" label="确认密码：" required>
                                        <el-input clearable v-model="userForm.password2" size="small" placeholder="请输入确认密码"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-collapse-item>
                        <el-collapse-item>
                            <template slot="title">
                                <i class="el-icon-s-order"></i>&nbsp;详细信息
                            </template>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item prop="name" label="用户昵称：" required>
                                        <el-input clearable v-model="userForm.name" size="small" placeholder="请输入用户昵称"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                     <el-form-item prop="realName" label="用户姓名：" required>
                                        <el-input clearable v-model="userForm.realName" size="small" placeholder="请输入用户姓名"></el-input>
                                     </el-form-item>
                                </el-col>
                            </el-row>
                             <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item prop="phone" label="手机号码：">
                                        <el-input clearable v-model="userForm.phone" size="small" placeholder="请输入手机号码"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item prop="email" label="电子邮箱：">
                                         <el-input clearable v-model="userForm.email" size="small" placeholder="请输入电子邮箱"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                             <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="用户性别：" prop="sex">
                                        <el-select v-model="userForm.sex" placeholder="请选择用户性别" size="small">
                                            <el-option label="男" value="1"></el-option>
                                            <el-option label="女" value="2"></el-option>
                                            <el-option label="未知" value="3"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="用户生日：" prop="birthday">
                                        <el-date-picker v-model="userForm.birthday" type="datetime" size="mini" placeholder="选择日期"></el-date-picker>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-collapse-item>
                        <el-collapse-item>
                             <template slot="title">
                                <i class="el-icon-s-custom"></i>&nbsp;职责信息
                             </template>
                               <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="用户编号：" prop="code">
                                    <el-input clearable v-model="userForm.code" size="small" placeholder="请输入用户编号"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="所属角色：" required prop="$roleId">
                                 <el-select v-model="userForm.$roleId" placeholder="请选择所属角色" size="mini" style="width: 100%">
                                     <el-input
                                            placeholder="输入关键字进行过滤"
                                            style="padding: 10px;width: 96%"
                                            size="mini"
                                            v-model="roleFilter">
                                        </el-input>
                                        <el-option :value="roleValue" :label="roleLabel" style="height: auto">
                                        <el-tree ref="roleTree" show-checkbox :data="selectRoleTree" highlight-current :filter-node-method="filterNode" @check-change="handleRoleChange"></el-tree>
                                 </el-option>
                               </el-select>
                            </el-form-item>
                            </el-col>
                          </el-row>
                           <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="所属部门：" required prop="$deptId">
                                    <el-select v-model="userForm.$deptId" placeholder="请选择所属部门" size="mini" style="width: 100%">
                                        <el-input
                                            placeholder="输入关键字进行过滤"
                                            style="padding: 10px;width: 96%"
                                            size="mini"
                                            v-model="filterText">
                                        </el-input>
                                        <el-option :value="depetValue" :label="depetLabel" style="height: auto">
                                           <el-tree ref="tree" :data="selectDeptTree" show-checkbox highlight-current check-strictly :filter-node-method="filterNode" @check-change="handleDeptChange"></el-tree>
                                       </el-option>
                                    </el-select>
                            </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="所属岗位：" required prop="$postId">
                                <el-select v-model="userForm.$postId" placeholder="请选择岗位" size="mini" style="width: 100%">
                                     <el-input
                                        placeholder="输入关键字进行过滤"
                                        size="mini"
                                        v-model="filterPostText"
                                        style="margin-bottom: 10px">
                                        </el-input>
                                    <el-option style="height: auto;" :label="postLabel" :value="postValue">
                                         <el-tree class="filter-tree" :data="postList"
                                            show-checkbox
                                            @check-change="handlePostChange"
                                            check-strictly
                                            :filter-node-method="filterPostNode">
                                         </el-tree>
                                    </el-option>
                                </el-select>
                            </el-form-item>
                            </el-col>
                          </el-row>
                        </el-collapse-item>
                    </el-collapse>
                </el-form>
             <div style="margin: 10px;text-align: right">
                    <el-button type="primary" size="small" @click="handleSubmit(['userForm'])">保存</el-button>
                    <el-button size="small">取消</el-button>
            </div>
        </el-drawer>
        <!-- 用户数据导入 -->
        <el-dialog
        title="用户数据导入"
        :visible.sync="importDialog"
        width="30%"
        :before-close="handleClose">
             <el-form :model="uploadForm" :rules="uploadRules" ref="uploadForm">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item  prop="scopeName" label="模板上传：" required :label-width="formLabelWidth">
                        <el-upload
                                class="upload-demo"
                                drag
                                action="https://jsonplaceholder.typicode.com/posts/"
                                multiple>
                                <i class="el-icon-upload"></i>
                                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                                <div class="el-upload__tip" slot="tip">请上传 .xls,.xlsx 标准格式文件</div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="12">
                          <el-form-item  prop="scopeName" label="数据覆盖：" required :label-width="formLabelWidth">
                              <el-switch
                                active-text="是"
                                inactive-text="否">
                              </el-switch>
                          </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                       <el-form-item  prop="scopeName" label="模板下载：" required :label-width="formLabelWidth">
                           <el-button type="primary" size="small">点击下载<i class="el-icon-download"></i></el-button>
                       </el-form-item>
                  </el-col>
                </el-row>
             </el-form>
        </el-dialog>

        <!-- 角色配置 -->
        <el-dialog title="用户角色配置" :visible.sync="roleDialog" width="20%">
            <el-tree
                :data="roleData"
                node-key="id"
                :props="defaultProps"
                :default-checked-keys="defaultRoleChecked"
                @check-change="handleCheckChange"
                show-checkbox>
            </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="powerDialog = false" size="small">取 消</el-button>
                <el-button type="primary" @click="handleRoleSave" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {getDeptList} from '@/api/system/dept.api.js'
    import {getUserList,getPostSelect,getDeptTree,getRoleTree,saveUser,resetPassword,saveRole,remove} from '@/api/system/user.api.js'
    import {getParentTree} from '@/api/authority/role.api'
    import { format } from '@/utils/index'
    export default {
        data() {
             var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'))
                } else if (value !== this.userForm.password) {
                    callback(new Error('两次输入密码不一致!'))
                } else {
                    callback()
                }
            }
            return {
                 queryParams: {
                      current: 1,
                      size: 10,
                      account: undefined,
                      realName: undefined,
                      deptId: undefined
                  },
                  total: 0,
                 filterText: '',
                 data: [],
                 postList: [],
                 filterPostText: '',
                 postValue: '',
                 postLabel: '',
                 props: {
                    label: 'name',
                    children: 'zones',
                    isLeaf: 'leaf'
                },
                tableData: [],
                // 抽屉
                drawer: false,
                userForm: {
                    account: '',
                    password: '',
                    password2: '',
                    phone: '',
                    email: '',
                    sex: '',
                    name: '',
                    realName: '',
                    $deptId: '',
                    $roleId: '',
                    $postId: '',
                    birthday: ''
                },
                selectDeptTree:[],
                selectRoleTree: [],
                userRules: {
                      account: [
                        { required: true, message: '请输入登录账号', trigger: 'blur' },
                      ],
                       password: [
                        { required: true, message: '密码不能为空', trigger: 'blur' },
                        { pattern: /^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*)/, message: '密码必须包含大小写字母、数字', trigger: 'blur' },
                      ],
                       password2: [
                        { validator: validatePass2, trigger: 'blur' },
                      ],
                       name: [
                        { required: true, message: '请输入用户昵称', trigger: 'blur' },
                      ],
                       realName: [
                        { required: true, message: '请输入用户姓名', trigger: 'blur' },
                      ],
                      dept: [{required: true,message: '请选择所属部门',trigger: 'blur'}]
                },
                // 用户数据导入弹窗
                importDialog: false,
                formLabelWidth: '120px',
                uploadRules: {},
                uploadForm: {},
                depetLabel: '',
                depetValue: '',
                roleFilter: '',
                roleLabel: '',
                roleValue: '',
                roleSelect: [],
                deptNameArr: [],
                deptIdArr: [],
                roleNameArr: [],
                roleIdArr: [],
                postNameArr: [],
                postIdArr: [],
                roleDialog: false,
                roleData: [
                 ],
                 defaultProps: {
                    children: 'children',
                    label: 'label'
                 },
                 roleChecked: [],
                 defaultRoleChecked: [],
                 mode: 'add'
            }
        },
        watch: {
            filterText(val) {
                this.$refs.tree.filter(val);
            },
            roleFilter(val) {
                this.$refs.roleTree.filter(val);
            }
        },
        mounted() {
            this.getPostData();
        },
        methods: {
            async getPostData() {
              const result = await getPostSelect(this.queryParams);
              if(result.code === 200) {
                  this.postList = result.data.map(item=>{
                      return {
                          label: item.postName,
                          id: item.id
                      }
                  })
              }
            },
              // 搜索
            handleQuery() {
                this.queryParams.current = 1;
                this.getList();
            },
            // 清空
            resetQuery(formName) {
                this.$refs[formName].resetFields();
                this.getList();
            },
            handleSizeChange(val) {
                this.queryParams.size = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.queryParams.current = val;
                this.getList();
            },
            handleImport() {
                this.importDialog = true;
            },
            filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            },
            loadNode(node, resolve) {
                  if (node.level === 0) {
                      let params = {parentId: 0}
                        getDeptList(params).then(res=>{
                            if(res.code===200) {
                            let data = res.data
                            const nodeArr = data.map(item=>{
                                return {
                                    name: item.fullName,
                                    leaf:!item.hasChildren,
                                    ...item,
                                }
                            })
                            return resolve(nodeArr)
                        }
                        })
                   }else {
                         let params = {parentId: node.data.id}
                        getDeptList(params).then(res=>{
                            if(res.code===200) {
                            let data = res.data
                            const nodeArr = data.map(item=>{
                                return {
                                    name: item.fullName,
                                    leaf:!item.hasChildren,
                                    ...item,
                                    
                                }
                            })
                            return resolve(nodeArr)
                            }
                        })
                    }
            },
            getList() {
                getUserList(this.queryParams).then(res=>{
                     if(res.code===200) {
                         this.tableData = res.data.records;
                         this.total = res.data.total;
                     }
                })
            },
            handleNodeClick(data)  {
                this.queryParams.deptId = data.id;
                this.getList();
            },
            getTreeNode(data) {
                data.forEach(item => {
                    item.label = item.title;
                    if(item.hasChildren) {
                        this.getTreeNode(item.children);
                    }
                });
                return data;
            },
            async handleAdd() {
                this.mode = 'add'
                this.roleSelect = []
               this.drawer = true;
               const result = await getDeptTree();
               if(result.code === 200) {
                  this.selectDeptTree = this.getTreeNode(result.data);
               }
               const result2 = await getParentTree();
                if(result2.code === 200) {
                  this.selectRoleTree = this.getTreeNode(result2.data);
               }
            },
            handleDelete(id) {
                this.$confirm('确定将选择的数据删除?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).then(async () => {
                        const result = await remove(id);
                        if(result.code === 200) {
                             this.$message({
                                type: 'success',
                                message: '删除成功!'
                           });
                           this.getList();
                        }
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });          
                });
            },
            handleClose() {
               this.drawer = false;
            },
             handleEdit(row) {
                this.userForm = row;
                this.drawer = true;
                this.mode = 'edit'
            },
            handleView(row) {
                this.userForm = row;
                this.drawer = true;
                this.mode = 'view'
            },
            handleSubmit(formName) {
                this.$refs[formName].validate(async(valid) => {
                    if (valid) {
                    //    this.userForm.birthday = format(this.userForm.birthday)
                       const result = await saveUser(this.userForm);
                       if(result.code === 200) {
                            this.$message.success('保存成功');
                            this.drawer=false;
                            this.getList();
                       }
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            filterPostNode(value, data) {
                if (!value) return true;
                    return data.label.indexOf(value) !== -1;
            },
            handleDeptChange(data, checked) {
                if(checked) {
                    this.deptNameArr.push(data.label);
                    this.deptIdArr.push(data.id);
                }else {
                    this.deptNameArr = this.deptNameArr.filter(item=>item !== data.label)
                    this.deptIdArr = this.deptIdArr.filter(item=>item !== data.id)
                }
                this.userForm.$deptId = this.deptNameArr.join(' | ')
                this.userForm.deptId = this.deptIdArr.join(',')
                
            },
            handleRoleChange(data, checked) {
                if(checked) {
                    this.roleNameArr.push(data.label);
                    this.roleIdArr.push(data.id);
                }else {
                    this.roleNameArr = this.roleNameArr.filter(item=>item !== data.label)
                    this.roleIdArr = this.roleIdArr.filter(item=>item !== data.id)
                }
                this.userForm.$roleId = this.roleNameArr.join(' | ');
                this.userForm.roleId = this.roleIdArr.join(',')
            },
            handlePostChange(data, checked) {
                if(checked) {
                    this.postNameArr.push(data.label);
                    this.postIdArr.push(data.id);
                }else {
                    this.postNameArr = this.postNameArr.filter(item=>item !== data.label)
                    this.postIdArr = this.postIdArr.filter(item=>item !== data.id)
                }
                this.userForm.$postId = this.postNameArr.join(' | ');
                this.userForm.postId = this.postIdArr.join(',')
            },
            // 密码重置
            handleReset() {
                if(this.$refs.tableRef.selection.length === 0) {
                    this.$message.warning('请至少选择一条数据');
                    return;
                }
                this.$confirm('确定将选择账号密码重置为【AsdF1234!】?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const ids = this.$refs.tableRef.selection.map(item=>item.id)
                    const result = await resetPassword(ids);
                    if(result.code === 200) {
                            this.$message({
                            type: 'success',
                            message: '重置成功!'
                        });
                        this.getList();
                    }else {
                        this.$message.error(result.data.msg);
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消重置'
                    });          
                });
            },
            async handleRoleSet() {
                if(this.$refs.tableRef.selection.length === 0) {
                    this.$message.warning('请至少选择一条数据');
                    return;
                }
                const result = await getRoleTree();
                if(result.code === 200) {
                    this.roleData = this.getTreeNode(result.data);
                    this.roleDialog = true;
                }
                 if(this.$refs.tableRef.selection.length === 1) {
                    this.defaultRoleChecked = this.$refs.tableRef.selection[0].roleId.split(',')
                }
            },
            async handleRoleSave() {
                const userIds = this.$refs.tableRef.selection.map(item=>item.id).join(',');
                const roleIds = this.roleChecked.join(',');
                const result = await saveRole(userIds,roleIds);
                if(result.code === 200) {
                    this.$message.success('保存成功');
                    this.roleDialog = false;
                    this.getList();
                }
            },
            handleCheckChange(data, checked) {
                if(checked) {
                    this.roleChecked.push(data.id);
                }else {
                    this.roleChecked = this.roleChecked.filter(item=>item !== data.id)
                }
            },
            download() {
                download
            }
        }
    }
</script>

<style lang="scss" scoped>
.user-btns {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    margin: 10px;
}
::v-deep .el-collapse-item__header {
    font-size: 18px;
    padding: 30px 0 5px 0;
}
::v-deep .el-collapse {
    padding: 0 30px;
}
::v-deep .el-select-dropdown__item.hover, .el-select-dropdown__item:hover {
     background-color: #fff;
}
.pagination-container {
    padding: 10px;
    text-align: right;
}
</style>